package level4.helpers
{
	import flash.display.Stage;
	import flash.events.Event;
	import flash.utils.clearInterval;
	import flash.utils.clearTimeout;
	import flash.utils.getTimer;
	import flash.utils.setInterval;
	import flash.utils.setTimeout;
	
	import level4.engines.components.GameComponent;

	/**
	 * 定时器 辅助类
	 * **/
	public class TimerHelper
	{
		/**延迟执行*/
		public static function setTimeoutTask(fun:Function,millisecond:int,...params):void{
			var timerId:int = setTimeout(function(...params):void{
				clearTimeout(timerId);
				try{
					fun.call(null,params);
				}catch(e:*){}
			},millisecond,params);
		}
		/**延迟执行并限制执行次数,返回timerId*/
		public static function setIntervalTaskLimitnum(callFun:Function, millisecond:int, limitNum:int = 1, doneFun:Function = null, ...params):uint{
			var i:int = 0;
			if(limitNum <= 0)
				limitNum = 1;
			var timerId:uint = setInterval(function(...params):void{
				if(i == limitNum)
				{
					clearInterval(timerId);
					if(doneFun != null)
						doneFun.call();
				}
				else
					callFun.call(null,params);
				i++;
			},millisecond,params);
			
			return timerId;
		}
		
		/**数字转时间*/
		public static function numberToDate(time:Number):Date
		{
			var date:Date = new Date();
			date.time = time;
			return date;
		}
		
		/**数字转时间字符串*/
		public static function dateToLoacalString(value:*):String
		{
			var date:Date;
			if(value is Number)
			{
				date = new Date();
				date.time = value;
			}else if(value is String)
			{
				date = new Date(value);
			}else
				date = value;
			
			var year:int = date.fullYear;
			var mounth:int = date.month + 1;
			var day:int = date.date;
			var hour:int = date.hours;
			var min:int = date.minutes;
			var sec:int = date.seconds;
			//return year+"年"+mounth+"月"+day+"日"+" "+hour+"时"+min+"分"+sec+"秒";
			return year+"-"+mounth+"-"+day+" "+hour+":"+min+":"+sec;
		}
		/**
		 * 秒数 -> 时:分:秒
		 * */
		public static function SecondToHHMMSS(seconds:Number):String{
			var m:int = seconds / 60;
			var s:Number = seconds % 60;
			var h:int = m / 60;
			m %= 60;
			
			return format(h.toString())+":"+ format(m.toString()) +":"+ format(s.toString());
//			return h+":"+m+":"+s;
			
			function format(str:String):String{
				if(str.length == 1){
					return 0+str;
				}
				return str;
			}
		}
		
		/**
		 * 计时
		 * */
		private static var gameComp:GameComponent;
		private static var lastTime:Number;
		/**
		 * 开始 计时
		 * */
		public static function StartTiming():void{
			if(!gameComp){
				gameComp = new GameComponent(update);
				lastTime = 0;
			}
			////////
			//闭包
			////////
			function update(timeDiff:Number):void{
				lastTime += timeDiff;
			}
		}
		/**
		 * 结束计时,并返回经过的时间
		 * */
		public static function StopTiming():Number{
			if(gameComp){
				gameComp.dispose();
			}
			return lastTime;
		}
	}
}